<!DOCTYPE html>
<html lang="zh-cn">
    <head>
        <meta charset="UTF-8">
        <title>新增页面</title>
        <link rel="stylesheet" href="/app/admin/component/pear/css/pear.css" />
        <link rel="stylesheet" href="/app/admin/component/jsoneditor/css/jsoneditor.css" />
        <link rel="stylesheet" href="/app/admin/admin/css/reset.css" />
    </head>
    <body>

        <form class="layui-form" action="">

            <div class="mainBox">
                <div class="main-container mr-5">
                    <div class="layui-form-item">
                        <label class="layui-form-label required">章节名称</label>
                        <div class="layui-input-block">
                            <input type="text" name="name" placeholder="" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label required">章节序号</label>
                        <div class="layui-input-block">
                            <input type="number" name="number" placeholder="" class="layui-input">
                        </div>
                    </div>
                    <div style="display: flex;flex-direction: row;align-items: center">
                        <div class="layui-form-item" style="width: 50%">
                            <label class="layui-form-label required">原文内容</label>
                            <div class="layui-input-block">
                                <tip style="color: red"> 当前字数：<span class="original_char_nums">0</span></tip>
                                <textarea name="original_content" class="layui-textarea" rows="15" cols="27" onblur="comput_original_nums()"></textarea>
                            </div>
                        </div>
                        <div class="layui-form-item"  style="width: 50%">
                            <label class="layui-form-label">原文分析AI指令：</label>
                            <div class="layui-input-block">
                                <tip style="color: red;font-size: 12px;">@content 作为内容替换</tip>
                                <textarea name="original_content_ai_command" class="layui-textarea" rows="15"  cols="23"><?=htmlspecialchars($original_content_ai_command)?></textarea>
                            </div>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label"></label>
                        <button type="button" class="pear-btn pear-btn-primary pear-btn-md original_content_analyze">
                            原文分析
                        </button>
                    </div>
                    <div style="display: flex;flex-direction: row;align-items: center">
                        <div class="layui-form-item" style="width: 50%">
                            <label class="layui-form-label required">分析内容</label>
                            <div class="layui-input-block">
                                <tip style="color: red"> 当前字数：<span class="analyze_char_nums">0</span></tip>
                                <textarea name="analyze_content" class="layui-textarea" rows="15" cols="27" onblur="comput_analyze_nums()"></textarea>
                            </div>
                        </div>
                        <div class="layui-form-item"  style="width: 50%">
                            <label class="layui-form-label">内容换行AI指令：</label>
                            <div class="layui-input-block">
                                <tip style="color: red;font-size: 12px;">@content 作为内容替换</tip>
                                <textarea name="content_parts_ai_command" class="layui-textarea" rows="15"  cols="23"><?=htmlspecialchars($content_parts_ai_command)?></textarea>
                            </div>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label"></label>
                        <button type="button" class="pear-btn pear-btn-primary pear-btn-md analyze_content_parts">
                            内容分段
                        </button>
                    </div>
                    <div style="display: flex;flex-direction: row;align-items: center">
                        <div class="layui-form-item" style="width: 50%">
                            <label class="layui-form-label required">分段内容</label>
                            <div class="layui-input-block">
                                <tip style="color: red">换行作为分段的隔离符   当前段落数：<span class="part_nums">0</span></tip>
                                <textarea name="content" class="layui-textarea" rows="15" cols="27" onblur="comput_part_nums()"></textarea>
                            </div>
                        </div>
                        <div class="layui-form-item"  style="width: 50%">
                            <label class="layui-form-label">生成描述词AI指令：</label>
                            <div class="layui-input-block">
                                <tip style="color: red;font-size: 12px;">@content 作为内容替换</tip>
                                <textarea name="batch_prompt_ai_command" class="layui-textarea" rows="15"  cols="23"><?=htmlspecialchars($batch_prompt_ai_command)?></textarea>
                            </div>
                        </div>
                    </div>
                    <div class="layui-form-item" style="display: none;">
                        <label class="layui-form-label required">GPT版本</label>
                        <div class="layui-input-block gptversion">
                            <input type="radio" name="name" value="gpt-4" title="gpt-4" checked>
                            <input type="radio" name="name" value="gpt-3" title="gpt-3">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label"></label>
                        <button type="button" class="pear-btn pear-btn-primary pear-btn-md batch_regenerate_prompt">
                            批量生成英文描述词
                        </button>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">英文描述词</label>
                        <div class="layui-input-block">
                            <tip style="color: red">当前段落数：<span class="analyze_part_nums">0</span></tip>
                            <textarea name="prompt_content" class="layui-textarea" rows="15" cols="80" onblur="comput_analyze_part_nums()"></textarea>
                        </div>
                    </div>
                    
                </div>
            </div>

            <div class="bottom">
                <div class="button-container">
                    <button type="submit" class="pear-btn pear-btn-primary pear-btn-md" lay-submit=""
                        lay-filter="save">
                        提交
                    </button>
                    <button type="reset" class="pear-btn pear-btn-md">
                        重置
                    </button>
                </div>
            </div>
            
        </form>

        <script src="/app/admin/component/layui/layui.js?v=2.8.12"></script>
        <script src="/app/admin/component/pear/pear.js"></script>
        <script src="/app/admin/component/jsoneditor/jsoneditor.js"></script>
        <script src="/app/admin/admin/js/permission.js"></script>
        <script src="/app/admin/admin/js/functions.js"></script>
        <script src="/app/admin/admin/js/md5.js"></script>
        
        <script>
            let analyze_content_ai_command = '<?=htmlspecialchars($analyze_content_ai_command)?>';
            layui.$('textarea[name="analyze_content_ai_command"]').val(analyze_content_ai_command);

            // 相关接口
            const INSERT_API = "/app/admin/novel/chapter/insert";
            const AI_REGENERATE_API = "/app/admin/novel/chapter/airegenerate";
            const GPT_SELECT_API = "/app/admin/gptversion/index/select?limit=100";

            layui.use(["form", "common", "popup", "util"], function() {
                let loading = layer.load();
                let param = {"status":1};
                layui.$.ajax({
                    url: GPT_SELECT_API,
                    type: "GET",
                    dateType: "json",
                    data: param,
                    async:true,
                    headers: get_header(param),
                    success: function (res) {
                        layer.close(loading);
                        if (res.code) {
                            return layui.popup.failure(res.msg);
                        }
                        let html ='';
                        let checked ='';
                        layui.$.each(res.data,function (i,v) {
                            if(v['name']=='gpt-4o'){
                                checked ='checked';
                            }
                            html += '<input type="radio" name="gptversion" value="'+v.name+'" title="'+v.name+'" '+checked+'>';
                        })
                        $('.gptversion').html(html);

                        layui.form.render();
                    }
                });
            });

            //提交事件
            layui.use(["form", "popup","loading"], function () {
                layui.form.on("submit(save)", function (data) {
                    let prompt_content = layui.$('textarea[name="prompt_content"]').val();
                    let prompt_contents = prompt_content.split("\n");
                    let content = layui.$('textarea[name="content"]').val();
                    let contents = content.split("\n");
                    if(prompt_contents.length!=contents.length){
                        layer.msg('创作章节段落和英文描述词段落不一致',{"icon":2,"time":2000});
                        return false;
                    }

                    data.field['novel_sn'] = layui.url().search['novel_sn'];
                    let loading = layer.load();
                    layui.$.ajax({
                        url: INSERT_API,
                        type: "POST",
                        dateType: "json",
                        data: data.field,
                        async:true,
                        headers: get_header(data.field),
                        success: function (res) {
                            layer.close(loading);
                            if (res.code) {
                                return layui.popup.failure(res.msg);
                            }
                            return layui.popup.success("操作成功", function () {
                                parent.refreshTable();
                                parent.layer.close(parent.layer.getFrameIndex(window.name));
                            });
                        }
                    });
                    return false;
                });

                // layui.form.on("submit(regenerate_chapter)", function (data) {
                //     data.field['type'] = 'regenerate_chapter';
                //     let loadIndex = layui.loading.Load(1, "生成中...");
                //     layui.$.ajax({
                //         url: AI_REGENERATE_API,
                //         type: "POST",
                //         dateType: "json",
                //         data: data.field,
                //         async:true,
                //         headers: get_header(data.field),
                //         success: function (res) {
                //             layui.loading.loadRemove(1);
                //             if (res.code) {
                //                 return layui.popup.failure(res.msg);
                //             }
                //             return layui.popup.success("操作成功", function () {
                //                 layui.$('textarea[name="analyze_content"]').val(res.data.analyze_content);
                //                 layui.$('.analyze_part_nums').text(res.data.part_nums);
                //                 comput_analyze_part_nums()
                //             });
                //         },
                //         error:function (res) {
                //             layui.loading.loadRemove(1);
                //             return layui.popup.failure('请求失败');
                //         }
                //     });
                //     return false;
                // });
            });

            layui.use(["form", "popup","loading"], function () {
                layui.$('.original_content_analyze').click(function () {
                    let param = {};
                    param['original_content'] = layui.$('textarea[name="original_content"]').val();
                    param['original_content_ai_command'] = layui.$('textarea[name="original_content_ai_command"]').val();
                    param['type'] = 'original_content_analyze';

                    let loadIndex = layui.loading.Load(1, "生成中...");
                    layui.$.ajax({
                        url: AI_REGENERATE_API,
                        type: "POST",
                        dateType: "json",
                        data: param,
                        async:true,
                        headers: get_header(param),
                        success: function (res) {
                            layui.loading.loadRemove(1);
                            if (res.code) {
                                return layui.popup.failure(res.msg);
                            }
                            return layui.popup.success("操作成功", function () {
                                layui.$('textarea[name="analyze_content"]').val(res.data.analyze_content);
                                layui.$('.analyze_char_nums').text(res.data.analyze_nums);
                                comput_analyze_nums()
                            });
                        },
                        error:function (res) {
                            layui.loading.loadRemove(1);
                            return layui.popup.failure('请求失败');
                        }
                    });
                })

                layui.$('.analyze_content_parts').click(function () {
                    let param = {};
                    param['analyze_content'] = layui.$('textarea[name="analyze_content"]').val();
                    param['content_parts_ai_command'] = layui.$('textarea[name="content_parts_ai_command"]').val();
                    param['type'] = 'analyze_content_parts';

                    let loadIndex = layui.loading.Load(1, "生成中...");
                    layui.$.ajax({
                        url: AI_REGENERATE_API,
                        type: "POST",
                        dateType: "json",
                        data: param,
                        async:true,
                        headers: get_header(param),
                        success: function (res) {
                            layui.loading.loadRemove(1);
                            if (res.code) {
                                return layui.popup.failure(res.msg);
                            }
                            return layui.popup.success("操作成功", function () {
                                layui.$('textarea[name="content"]').val(res.data.content);
                                layui.$('.part_nums').text(res.data.part_nums);
                                comput_part_nums()
                            });
                        },
                        error:function (res) {
                            layui.loading.loadRemove(1);
                            return layui.popup.failure('请求失败');
                        }
                    });
                })

                layui.$('.batch_regenerate_prompt').click(function () {
                    let param = {};
                    param['content'] = layui.$('textarea[name="content"]').val();
                    param['gptversion'] = layui.$('input[name="gptversion"]:checked').val();
                    param['batch_prompt_ai_command'] = layui.$('textarea[name="batch_prompt_ai_command"]').val();
                    param['type'] = 'batch_regenerate_prompt';

                    let loadIndex = layui.loading.Load(1, "生成中...");
                    layui.$.ajax({
                        url: AI_REGENERATE_API,
                        type: "POST",
                        dateType: "json",
                        data: param,
                        async:true,
                        headers: get_header(param),
                        success: function (res) {
                            layui.loading.loadRemove(1);
                            if (res.code) {
                                return layui.popup.failure(res.msg);
                            }
                            return layui.popup.success("操作成功", function () {
                                layui.$('textarea[name="prompt_content"]').val(res.data.prompt_content);
                                layui.$('.analyze_part_nums').text(res.data.part_nums);
                                comput_analyze_part_nums()
                            });
                        },
                        error:function (res) {
                            layui.loading.loadRemove(1);
                            return layui.popup.failure('请求失败');
                        }
                    });
                })
            });

            function comput_original_nums() {
                let content = layui.$('textarea[name="original_content"]').val();
                let contents = content.split("\n");
                let nums = 0;
                let contentVal = '';
                $.each(contents,function (i,v) {
                    let text = v.replace(/[·|`|~|!|@|#|\$|\^|\&|\*|(|)|=|\||{|}|'|\\|\[|\]|<|>|《|》|\/|￥|……|（|）|——|_|+|-|{|}|【|】|‘|”|“|’|「|」]+/g,'');
                    text = text.replace(/^\d+[\.]*/,'');
                    if(text){
                        nums++;
                        contentVal += text+"\n";
                    }
                })
                layui.$('textarea[name="original_content"]').val(contentVal);

                $('.original_char_nums').text(getChineseLength(contentVal));
            }

            function comput_analyze_nums() {
                let content = layui.$('textarea[name="analyze_content"]').val();
                let contents = content.split("\n");
                let nums = 0;
                let contentVal = '';
                $.each(contents,function (i,v) {
                    let text = v.replace(/[·|`|~|!|@|#|\$|\^|\&|\*|(|)|=|\||{|}|'|\\|\[|\]|<|>|《|》|\/|￥|……|（|）|——|_|+|-|{|}|【|】|‘|”|“|’|「|」]+/g,'');
                    text = text.replace(/^\d+[\.]*/,'');
                    if(text){
                        nums++;
                        contentVal += text+"\n\n";
                    }
                })
                layui.$('textarea[name="analyze_content"]').val(contentVal);
                $('.analyze_char_nums').text(getChineseLength(contentVal));
            }

            function comput_part_nums() {
                let content = layui.$('textarea[name="content"]').val();
                let contents = content.split("\n");
                let nums = 0;
                let contentVal = '';
                $.each(contents,function (i,v) {
                    let text = v.replace(/[·|`|~|!|@|#|\$|\^|\&|\*|(|)|=|\||{|}|'|\\|\[|\]|<|>|《|》|\/|￥|……|（|）|——|_|+|-|{|}|【|】|‘|”|“|’|「|」]+/g,'');
                    text = text.replace(/^\d+[\.]*/,'');
                    if(text){
                        nums++;
                        contentVal += (parseInt(nums))+'.'+ text+"\n";
                    }
                })
                layui.$('textarea[name="content"]').val(contentVal);
                $('.part_nums').text(nums);
            }

            function comput_analyze_part_nums() {
                let content = layui.$('textarea[name="prompt_content"]').val();
                let contents = content.split("\n");
                let nums = 0;
                let contentVal = '';
                $.each(contents,function (i,v) {
                  let text = v.replace(/^[ ]*/,'');
                      text = text.replace(/^\d+[\.]*/,'');

                    if(text){
                        nums++;
                        contentVal += (parseInt(nums))+'.'+ text+"\n";
                    }

                })
                layui.$('textarea[name="prompt_content"]').val(contentVal);
                $('.analyze_part_nums').text(nums);

                if(parseInt($('.part_nums').text())!=nums){
                    layer.msg('创作章节段落和英文描述词段落不一致',{"icon":2,"time":2000});
                }
            }
        </script>

    </body>
</html>
